//
//  YCSignUpMapViewController.m
//  YCSchool
//
//  Created by yanglinxia on 16/4/29.
//  Copyright © 2016年 yanglinxia. All rights reserved.
//  报名点地图

#import "YCSignUpMapViewController.h"
#import <BaiduMapAPI_Map/BMKAnnotationView.h>
#import "BNCoreServices.h"
#import "BNRoutePlanModel.h"
#import "YCPaopaoView.h"

@interface YCSignUpMapViewController ()<BMKLocationServiceDelegate,BMKMapViewDelegate, BNNaviRoutePlanDelegate,BNNaviUIManagerDelegate>

/** 定位  */
@property (nonatomic, strong) BMKLocationService *locService;

/** 地图视图  */
@property (nonatomic, strong) BMKMapView *mapView;

/** 当前位置信息 */
@property (nonatomic, strong) BMKUserLocation *currentUseLocation;

/** 底部工具条  */
@property (nonatomic, strong) UIView *bottomView;

@end

@implementation YCSignUpMapViewController

#pragma mark - 懒加载

// 定位
- (BMKLocationService *)locService
{
    if (!_locService) {
        //初始化BMKLocationService
        _locService = [[BMKLocationService alloc]init];
        _locService.delegate = self;
    }
    return _locService;
}

// 地图
- (BMKMapView *)mapView
{
    if (!_mapView) {
        _mapView = [[BMKMapView alloc] initWithFrame:CGRectMake(0, 0,kScreenWidth, kScreenHeight - 49)];
        
        // 地图相关设置
        [_mapView setMapType:BMKMapTypeStandard];   //普通地图
        [_mapView setTrafficEnabled:NO];           //打开实时路况图层
        [_mapView setBaiduHeatMapEnabled:NO];      //打开百度城市热力图图层（百度自有数据）紫色显示
        _mapView.buildingsEnabled = YES;
        _mapView.showMapScaleBar =YES;//显示比例尺
        _mapView.showsUserLocation = YES;//显示定位层
        _mapView.zoomLevel = 15;//比例尺
        _mapView.logoPosition = BMKLogoPositionRightTop;//设置logo位置
    }
    return _mapView;
}

- (UIView *)bottomView
{
    if (!_bottomView) {
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight-49,kScreenWidth,49)];
        _bottomView.backgroundColor = [UIColor whiteColor];
        UIButton *backBtn = [[UIButton alloc] init];
        [backBtn setImage:[UIImage imageNamed:@"nav_back"] forState:UIControlStateNormal];
        backBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -17, 0, 0);
        [backBtn addTarget:self action:@selector(backBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView addSubview:backBtn];
        
        UIButton *navBtn = [[UIButton alloc] init];
        [navBtn setTitle:@"导航" forState:UIControlStateNormal];
        [navBtn addTarget:self action:@selector(navBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        navBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        [navBtn setTitleColor:[UIColor yc_colorWithRed:60 Green:230 Blue:230] forState:UIControlStateNormal];
        [_bottomView addSubview:navBtn];
        
        [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_bottomView);
            make.top.bottom.equalTo(_bottomView);
            make.width.equalTo(@55);
        }];
        
        [navBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(_bottomView).offset(-21);
            make.top.bottom.equalTo(_bottomView);
        }];
        
    }
    return _bottomView;
}

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    //启动定位
    [self.locService startUserLocationService];
    
    [self.view addSubview:self.mapView];
    [self.view addSubview:self.bottomView];
    
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(self.view);
        make.height.equalTo(@49);
    }];
    [self.mapView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.bottom.equalTo(self.bottomView.mas_top);
    }];
    
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    
    [_mapView viewWillAppear];
    _mapView.delegate = self;
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
    [_mapView viewWillDisappear];
    _mapView.delegate = nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - 点击事件
- (void)backBtnClick:(UIButton *)btn
{
    YCLogFunc
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)navBtnClick:(UIButton *)btn
{
    
    YCLogFunc
    if(![BNCoreServices_Instance isServicesInited])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:@"引擎尚未初始化完成，请稍后再试"
                                                           delegate:nil
                                                  cancelButtonTitle:@"我知道了"
                                                  otherButtonTitles:nil];
        [alertView show];
        return;
    }
    //起点
    BNRoutePlanNode *startNode = [[BNRoutePlanNode alloc] init];
    startNode.pos = [[BNPosition alloc] init];
    startNode.pos.x = self.currentUseLocation.location.coordinate.longitude;// 经
    startNode.pos.y = self.currentUseLocation.location.coordinate.latitude;// 纬
    startNode.pos.eType = BNCoordinate_BaiduMapSDK;
    
    //终点
    BNRoutePlanNode *endNode = [[BNRoutePlanNode alloc] init];
    endNode.pos = [[BNPosition alloc] init];
    endNode.pos.x = 114.077075;
    endNode.pos.y = 22.543634;
    endNode.pos.eType = BNCoordinate_BaiduMapSDK;
    
    [BNCoreServices_RoutePlan startNaviRoutePlan:BNRoutePlanMode_Highway naviNodes:@[startNode,endNode] time:nil delegete:self userInfo:nil];
}

#pragma mark - 内部控制
// 隐藏状态栏
- (BOOL)prefersStatusBarHidden
{
    return YES;
}

#pragma mark - 其它
// 添加一个标注
- (void)addAnnotation:(CLLocationCoordinate2D)coor title:(NSArray *)titles
{
    BMKPointAnnotation *annotation = [[BMKPointAnnotation alloc] init];
    annotation.coordinate = coor;
    if (!titles) {
        annotation.title = titles[0];
        annotation.subtitle = titles[1];
    }
    [self.mapView addAnnotation:annotation];
    //添加后立即显示
    [self.mapView selectAnnotation:annotation animated:YES];
}

#pragma mark - BMKLocationServiceDelegate
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    YCLog(@"当前定位成功，经度：%.6f 纬度:%.6f",userLocation.location.coordinate.longitude,userLocation.location.coordinate.latitude);
    [self.locService stopUserLocationService];//停止定位
    self.mapView.centerCoordinate = userLocation.location.coordinate;
    self.currentUseLocation = userLocation;
    
    // 添加标注
    [self addAnnotation:userLocation.location.coordinate title:nil];
    // 地理编码
//    CLGeocoder *Geocoder = [[CLGeocoder alloc]init];
//    CLGeocodeCompletionHandler handler = ^(NSArray *place,NSError *error){
//        for(CLPlacemark *placemark in place){
//            NSString *tmp = [[NSString alloc]init];
//            tmp = placemark.name;
//            if (tmp.length > 10) {
//                NSString *title = [tmp substringToIndex:15];
//                NSString *subtitle = [tmp substringFromIndex:15];
//                //添加标注:
//                [self addAnnotation:userLocation.location.coordinate title:@[title,subtitle]];
//            } else {
//                [self addAnnotation:userLocation.location.coordinate title:@[tmp,@""]];
//            }
//            [self.mapView updateLocationData:userLocation];
//        }
//    };
//    CLLocation *loc = [[CLLocation alloc]initWithLatitude:userLocation.location.coordinate.latitude longitude:userLocation.location.coordinate.longitude];
//    [Geocoder reverseGeocodeLocation:loc completionHandler:handler];
    
}

#pragma mark - BMKMapViewDelegate
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
    static NSString *pinID = @"PINid";
    BMKAnnotationView *pinView = [mapView dequeueReusableAnnotationViewWithIdentifier:pinID];
    if (pinView == nil) {
        pinView = [[BMKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pinID];
    }
    pinView.annotation = annotation;
    pinView.image = [UIImage imageNamed:@"坐标"];//标注视图
    pinView.canShowCallout = YES;
    YCPaopaoView *paoView = [[YCPaopaoView alloc] initWithWithFrame:CGRectMake(0, 0, 300, 121) callPhoneBtnClickBlock:^(NSString *phoneNumber) {
        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",phoneNumber]]]) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",phoneNumber]]];
        }
    }];
    pinView.paopaoView = [[BMKActionPaopaoView alloc]initWithCustomView:paoView];
    
    return pinView;
}


/**
 * 点击气泡时调用
 * @param mapView 地图View
 * @param views 选中的annotation views
 */
- (void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view
{
    YCLogFunc
    
}

#pragma mark - BNNaviRoutePlanDelegate

//算路成功回调
-(void)routePlanDidFinished:(NSDictionary *)userInfo
{
    YCLog(@"算路成功");
    // BN_NaviTypeReal真实导航
    // BN_NaviTypeSimulator模拟导航
    [BNCoreServices_UI showNaviUI: BN_NaviTypeReal delegete:self isNeedLandscape:YES];
    
    // 进入巡航页面(自动监测电子狗)
//    [BNCoreServices_UI showDigitDogUI:YES delegete:self];
}

//算路失败回调
- (void)routePlanDidFailedWithError:(NSError *)error andUserInfo:(NSDictionary *)userInfo
{
    YCLog(@"算路失败");
    if ([error code] == BNRoutePlanError_LocationFailed) {
        YCLog(@"获取地理位置失败");
    }
    else if ([error code] == BNRoutePlanError_RoutePlanFailed)
    {
        YCLog(@"定位服务未开启");
    }
}

//算路取消
-(void)routePlanDidUserCanceled:(NSDictionary*)userInfo {
    YCLog(@"算路取消");
}

#pragma mark - BNNaviUIManagerDelegate

//退出导航回调
-(void)onExitNaviUI:(NSDictionary*)extraInfo
{
    YCLog(@"退出导航页面");
}
//退出导航声明页面回调
- (void)onExitDeclarationUI:(NSDictionary*)extraInfo
{
    YCLog(@"退出导航声明页面");
}
//退出巡航回调
-(void)onExitDigitDogUI:(NSDictionary*)extraInfo
{
    NSLog(@"退出电子狗页面");
}

#pragma mark -允许竖屏、横屏
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return interfaceOrientation != UIInterfaceOrientationMaskPortraitUpsideDown;
}
- (BOOL)shouldAutorotate
{
    return YES;
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskAllButUpsideDown;
}

@end
